package xyz.xiaotugou.dataStructure.basic;

/**
 * 
 * @Title:  MyArray   
 * @Package xyz.xiaotugou.dataStructure   
 * @Description:   自定义一个数组：支持插入、删除、查询、自动扩容
 * @author: ysy    
 * @date:   2020年9月1日 上午10:11:44  
 * @version V1.0
 */
public class MyArray {

	// 数组
	private int[] array;
	
	// 数组长度
	private int size;

	public MyArray(int capacity) {
		this.array = new int[capacity];
		this.size = 0;//数组长度，默认置为0
	}

	public void insert(int element, int index) throws Exception {
		if(index<0 || index >size){
			throw new IndexOutOfBoundsException("超出数组实际范围!");
		}
		// 如果数组长度即将等于容量，进行扩容
		if(size >= array.length){
			resize();
		}
		// 从插入位置的元素开始，所有元素向后移位
		for (int i = size-1; i >= index; i--) {
			array[i+1] = array[i];
		}
		array[index] = element;
		// 数组长度+1
		size ++; 
	}
	
	public int delete(int index) throws Exception {
		if(index<0 || index >size){
			throw new IndexOutOfBoundsException("超出数组实际范围!");
		}
		int deletedElement = array[index];
		for (int i = index; i < size-1; i++) {
			array[i] = array[i+1];
		}
		size--;
		return deletedElement;
	}
	
	public int get(int index) throws Exception {
		if(index<0 || index >size){
			throw new IndexOutOfBoundsException("超出数组实际范围!");
		}
		return array[index];
	}
	
	private void resize() throws Exception {
		int[] arrayNew = new int[array.length*2];
		//从旧数组拷贝到新数组
        System.arraycopy(array, 0, arrayNew, 0, array.length);
        array = arrayNew;
	}
	
    /**
     * 输出数组
     */
	private void output(){
        for(int i=0; i<size; i++){
            System.out.println(array[i]);
        }
    }
	
	public static void main(String[] args) throws Exception {
        MyArray myArray = new MyArray(4);
        myArray.insert(0,3);
        myArray.insert(1,7);
        myArray.delete(3);
        myArray.output();
    }
	
}
